package com.mentalhealthplatform.utils.decryptUtils.property;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtils {

    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String FIXED_IV = "1234567890abcdef";  // 固定的 16 字节 IV

    // 确保密钥的长度为16字节
    public static String normalizeKeyLength(String secretKey) {
        if (secretKey.length() < 16) {
            return String.format("%-16s", secretKey).replace(' ', '0');
        }
        return secretKey.substring(0, 16);
    }

    // 加密方法
    public static String encrypt(String data, String secretKey) throws Exception {
        SecretKeySpec key = new SecretKeySpec(normalizeKeyLength(secretKey).getBytes(), "AES");
        IvParameterSpec iv = new IvParameterSpec(FIXED_IV.getBytes(StandardCharsets.UTF_8));
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    // 解密方法
    public static String decrypt(String encryptedData, String secretKey) throws Exception {
        SecretKeySpec key = new SecretKeySpec(normalizeKeyLength(secretKey).getBytes(), "AES");
        IvParameterSpec iv = new IvParameterSpec(FIXED_IV.getBytes(StandardCharsets.UTF_8));
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedData = cipher.doFinal(decodedData);
        return new String(decryptedData, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        try {
            String secretKey = "yourSecretKey";  // 16 字节密钥
            String plainText = "Hello, AES Encryption!";  // 明文

            // 调用加密方法
            String encryptedText = encrypt(plainText, secretKey);
            System.out.println("Encrypted Text: " + encryptedText);

            // 调用解密方法
            String decryptedText = decrypt("h7w2+OyoHemG9fLgzrCRig==", secretKey);
            System.out.println("Decrypted Text: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
